package cn.binux.config;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableConfigurationProperties(RedisProperties.class)
public class JedisClusterConfig {
	@Value("${spring.redis.cluster.nodes[0]}")
	private List<String> redisNodes;
	@Value("${spring.redis.pool.max-wait}")
	private Integer maxWait;
	@Value("${spring.redis.pool.max-idle}")
	private Integer maxIdle;
	@Value("${spring.redis.pool.min-idle}")
	private Integer minIdle;
	@Value("${spring.redis.timeout}")
	private int timeout;
	
	private RedisProperties redisProperties;
	JedisClusterConfig(RedisProperties rx){
		this.redisProperties=rx;
	}

	@Bean
	public JedisCluster getJedisCluster() {
		String[] cNodes = redisNodes.toArray(new String[] {});
		Set<HostAndPort> nodes = new HashSet<>();
		for (String cNode : cNodes) {
			String[] hp = cNode.split(":");
			nodes.add(new HostAndPort(hp[0], Integer.valueOf(hp[1])));
		}
		JedisPoolConfig poolConfig = new JedisPoolConfig();
		poolConfig.setMaxWaitMillis(maxWait);
		poolConfig.setMaxIdle(maxIdle);
		poolConfig.setMinIdle(minIdle);
		return new JedisCluster(nodes, timeout, poolConfig);
	}
}